﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using cn.sharesdk.unity3d;
using Pb;


public class Index : Game
{
    public ShareSDK ssdk;
    public GameObject PhoneLoginBtn;
    public GameObject WeiXinLoginBtn;
    EginUser user = EginUser.Instance;
    public UILabel myDebug;

    public UILabel DeBug;

    public GameObject PhonePanel;

    void Awake()
    {
        UIEventListener.Get(PhoneLoginBtn).onClick = ButtonClick;
        UIEventListener.Get(WeiXinLoginBtn).onClick = ButtonClick;
        ssdk.authHandler = OnAuthResultHandler;
        ssdk.shareHandler = OnShareResultHandler;
        ssdk.showUserHandler = OnGetUserInfoResultHandler;

    }




    void ButtonClick(GameObject button)
    {
        if (button.name == "PhoneLoginBtn")
        {
            //手机登陆
            user.loginControl = 0;
            //GameObject login = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)Resources.Load(HallPrafabPath.Login));            
            PhonePanel.SetActive(true);
            Destroy(gameObject);
        }
        else if (button.name == "WeiXinLoginBtn")
        {
            //微信登陆  
            WXLgoin();
        }

    }

    void WXLgoin()
    {
        user.loginControl = 1;
        if (Application.platform == RuntimePlatform.Android ||
        Application.platform == RuntimePlatform.IPhonePlayer)
        {
            myDebug.text = "登录中";
            ssdk.CancelAuthorize(PlatformType.WeChat);
            ssdk.Authorize(PlatformType.WeChat);

            return;
        }
        else
        {


        }
    }

    void OnAuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {

        Debug.Log("授权中");
        myDebug.text = "授权中";
        if (state == ResponseState.Success)
        {
            print("authorize success !" + "Platform :" + type);
            Debug.Log("授权成功");
            myDebug.text = "授权成功";
            ssdk.GetUserInfo(PlatformType.WeChat);
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }

    void OnShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            print("share successfully - share result :");
            print(MiniJSON.jsonEncode(result));
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }

    void OnGetUserInfoResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            /*          
          { 
          "openid":"OPENID",
          "nickname":"NICKNAME",
          "sex":1,
          "province":"PROVINCE",
          "city":"CITY",
          "country":"COUNTRY",
          "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
          "privilege":[
          "PRIVILEGE1", 
          "PRIVILEGE2"
          ],
          "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

          }
          openid	普通用户的标识，对当前开发者帐号唯一
          nickname	普通用户昵称
          sex	普通用户性别，1为男性，2为女性
          province	普通用户个人资料填写的省份
          city	普通用户个人资料填写的城市
          country	国家，如中国为CN
          headimgurl	用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
          privilege	用户特权信息，json数组，如微信沃卡用户为（chinaunicom）
          unionid	用户统一标识。针对一个微信开放平台帐号下的应用，同一用户的unionid是唯一的。
            
          
           
            PlayerPrefs.SetString("faceurl", result["headimgurl"] as string);
            string sex = "";
            sex = result["sex"].ToString();      
            int ht = int.Parse(sex);           
            PlayerPrefs.SetInt("ht", ht);            
            Debug.Log("数据获取成功");
            PlayerPrefs.SetString("name", result["nickname"] as string);
            //存储发送登录消息
            GetUserInfoAndSendLogin(result);*/
            myDebug.text = "数据获取成功";
            Debug.Log("数据获取成功");
            //存储用户信息
            Debug.Log("headimgurl:" + result["headimgurl"] as string);
            Debug.Log("sex:" + result["sex"] as string);
            Debug.Log("nickname:" + result["nickname"] as string);
            Debug.Log("unionid:" + result["unionid"] as string);
            DeBug.text = MiniJSON.jsonEncode(result);
            Debug.Log(MiniJSON.jsonEncode(result));
            DeBug.text += "headimgurl:" + result["headimgurl"] as string + "\t";

            DeBug.text += "sex:" + result["sex"] as string + "\t";

            DeBug.text += "nickname:" + result["nickname"] as string + "\t";

            DeBug.text += "unionid:" + result["unionid"] as string;
            Debug.Log("输出完毕");
            string sex = "";
            sex = result["sex"].ToString();
            int ht = int.Parse(sex);
            if (ht == 0 || ht == 1)
            {
                user.sex = SEX.Male;
            }
            else
            {
                user.sex = SEX.Female;
            }

            Debug.Log("性别加载完毕");
            user.Uid = result["unionid"] as string;
            user.nickname = result["nickname"] as string;
            //用户的url获取
            //user.a = result["headimgurl"] as string;

            Debug.Log("性别加载完毕");
            user.userUrl = result["headimgurl"] as string;
            StartCoroutine("GetWWWFACE", result["headimgurl"] as string);

            Debug.Log("头像加载完毕");
            //获取设备
            string dev_name = SystemInfo.deviceModel;      //SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel)  //ProtoDataToMsg.stringToUTF8("小米");  
            string dev_number = SystemInfo.deviceUniqueIdentifier;

            Debug.Log("获取设备成功");
            //发送登录信息
            //Username = ProtoDataToMsg.stringToUTF8(user.username),
            Debug.Log("微信类型" + CHANNEL_TYPE.Weixin);
            Debug.Log("用户ID" + ProtoDataToMsg.stringToUTF8(user.Uid));
            Debug.Log(user.sex);
            Debug.Log(dev_number);
            ProtoDataToMsg.stringToUTF8("用户头像" + user.userUrl);

            LoginRequest lg = new Pb.LoginRequest { Channel = CHANNEL_TYPE.Weixin, Username = ProtoDataToMsg.stringToUTF8(user.Uid), Nickname = ProtoDataToMsg.stringToUTF8(user.nickname), Sex = user.sex, DevNumber = dev_number, AvatarUrl = ProtoDataToMsg.stringToUTF8(user.userUrl) };
            PlayerPrefs.SetString("username", ProtoDataToMsg.stringToUTF8(user.Uid));
            PlayerPrefs.SetString("nickname", ProtoDataToMsg.stringToUTF8(user.nickname));
            PlayerPrefs.SetInt("Sex", ht);
            PlayerPrefs.SetString("AvatarUrl", ProtoDataToMsg.stringToUTF8(user.userUrl));
            PlayerPrefs.SetInt("autologin", 1);
            EginUser.Instance.nickname = ProtoDataToMsg.stringToUTF8(user.nickname);
            Debug.Log("存储信息完毕");
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.LoginRequest);
            Debug.Log("发送消息完毕");
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }
    IEnumerator GetWWWFACE(string url)
    {

        if (url != "")
        {
            WWW www = new WWW(url);


            yield return www;
            if (www.isDone)
            {
                if (www.error == null) { }
                //user.avatar.mainTexture = www.texture;                
            }
            else
            {

            }
            www.Dispose();
        }

    }
}
